package com.mango.module.base.job;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.alibaba.fastjson.JSON;
import com.mango.module.base.Constant;
import com.mango.module.base.Constant.PushType;
import com.mango.module.base.config.PipelineConfig;
import com.mango.module.base.config.SpringContextUtils;
import com.mango.module.base.dto.PushData;
import com.mango.module.ldap.LdapUtil;
import com.mango.module.ldap.domain.DepartDO;
import com.mango.module.ldap.service.IDepartService;
import com.mango.module.util.QueueUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * ldap定时获取部门
 * @author Mango-Lab
 * @Date 2021年4月8日
 */

public class LdapDepartTask {
	

	/**
	 * 启动
	 */
	public static void start() {
		long delay= 30;
		long period= 24 * 60 * 60;
		System.out.println("ldap定时获取部门，延迟"+delay+"秒启动，周期："+period+"秒");
		Timer timer = new Timer();
		timer.schedule(new DepartTask(), delay * 1000, period * 1000);
	}
}

@Slf4j
class DepartTask extends TimerTask {

	@Override
	public void run() {
		log.info("==========================同步部门 START=============================》");
		IDepartService departService = SpringContextUtils.getBean(IDepartService.class);
		QueueUtils queueUtils = SpringContextUtils.getBean("queueUtils", QueueUtils.class);
		/**
		 * 1、获取获取部门
		 */
		PipelineConfig pConfig=SpringContextUtils.getBean(PipelineConfig.class);
		String basedn = pConfig.getLdapbase();//"dc=njupt,dc=edu,dc=cn";  // basedn
		List<DepartDO> list = LdapUtil.readGroup(basedn);
		if (list == null || list.size() == 0) {
			log.info("没有要同步的数据！");
			return;
		}
		int len = list.size();
		DepartDO temp = null;
		DepartDO depart = null;
		for (int i = 0; i < len; i++) {
			depart = list.get(i);
			temp = departService.getDepartByOu(depart.getCode());
			if (temp == null) {
				// 新增
				departService.addDO(depart);
				log.info("add-depart:{}", JSON.toJSONString(depart));
				queueUtils.send(Constant.MQ_QUEUE_KEY, JSON.toJSONString(new PushData(PushType.DEPART_ADD,depart)));
				continue;
			}
			// 删除、修改无法判断
		}

		log.info("《=========================同步部门END==============================");
	}
}